package com.itcast.jdbc.test03;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class JdbcTest01 {
    public static void main(String[] args) throws SQLException {
        //练习查询所有!!!!
        List<Brand> brands = queryAll();
        for (Brand brand : brands) {
            System.out.println(brand);
        }
    }
    public static List<Brand> queryAll() throws SQLException {
        List<Brand> result=new ArrayList<>();
        //1.获取连接
        Connection connection = DatasourceUtils.getConnection();
        //2.编写sql语句
        String sql="select * from tb_brand";
        //3.用preparedStatement包裹起来
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //4.查询结果
        ResultSet resultSet = preparedStatement.executeQuery();
        //5.解析使用结果
        while (resultSet.next()){
            //获取数据 第一个id
            int id = resultSet.getInt("id");
            String brandName = resultSet.getString("brand_name");
            String companyName = resultSet.getString("company_name");
            int ordered = resultSet.getInt("ordered");
            String description = resultSet.getString("description");
            int status = resultSet.getInt("status");

            //包装成一个对象
            Brand brand = new Brand();
            brand.setId(id);
            brand.setBrandName(brandName);
            brand.setCompanyName(companyName);
            brand.setOrdered(ordered);
            brand.setDescription(description);
            brand.setStatus(status);

            result.add(brand);
        }
        //6.关闭资源
        resultSet.close();
        preparedStatement.close();
        connection.close();

        return result;
    }
}
